package org.spider.api.domain.utilDomain;

import lombok.Data;
import org.spider.api.annotation.Comment;
import org.spider.api.annotation.Example;
import org.spider.api.annotation.Return;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 语法装配所需要用到的信息，例如类名，方法，描述，例子，返回值<br>
 * 用来生成前端的语法帮助文档使用
 */
@Data
public class Grammer {
	
	private String owner;

	private String method;
	
	private String comment;
	
	private String example;
	
	private String function;
	
	private List<String> returns;

	/**
	 * 把当前类中所声明的函数以及注解都转换为grammmer 并装到数组中
	 * @return
	 */
	public static List<Grammer> findGrammers(Class<?> clazz,String function,String owner,boolean mustStatic){
		Method[] methods = clazz.getDeclaredMethods();
		List<Grammer> grammers = new ArrayList<>();
		for (Method method : methods) {
			//公共属性
			if(Modifier.isPublic(method.getModifiers()) && (Modifier.isStatic(method.getModifiers())||!mustStatic)){
				Grammer grammer = new Grammer();
				grammer.setMethod(method.getName());
				Comment comment = method.getAnnotation(Comment.class);
				if(comment != null){
					grammer.setComment(comment.value());
				}
				Example example = method.getAnnotation(Example.class);
				if(example != null){
					grammer.setExample(example.value());
				}
				Return returns = method.getAnnotation(Return.class);
				if(returns != null){
					Class<?>[] clazzs = returns.value();
					List<String> returnTypes = new ArrayList<>();
					for (int i = 0; i < clazzs.length; i++) {
						returnTypes.add(clazzs[i].getSimpleName());
					}
					grammer.setReturns(returnTypes);
				}else{
					grammer.setReturns(Collections.singletonList(method.getReturnType().getSimpleName()));
				}
				grammer.setFunction(function);
				grammer.setOwner(owner);
				grammers.add(grammer);
			}
		}
		return grammers;
	}
}
